/*
 * @lc app=leetcode.cn id=106 lang=javascript
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
// 后续遍历反过来相当于反向的前序遍历
// 中序遍历也反过来操作
// 迭代版
// postorder = [3, 20, 7, 15, 9]
// inoreder = [7, 20, 15, 3, 9]
var buildTree = function(inorder, postorder) {
  inorder = inorder.reverse()
  postorder = postorder.reverse()
  const root = new TreeNode(postorder[0])
  const stack = [root]
  let inorderIndex = 0
  for (let i = 1; i < postorder.length; i++) {
    const postorderItem = postorder[i]

    let node = stack[stack.length - 1]

    if (node.val !== inorder[inorderIndex]) {
      // 当前分支的右节点推入堆栈
      node.right = new TreeNode(postorderItem)
      stack.push(node.right)
    } else {
      // 为右节点不做处理，节点退出堆栈
      while (stack.length && stack[stack.length - 1].val === inorder[inorderIndex]) {
        node = stack.pop()
        inorderIndex ++
      }
      node.left = new TreeNode(postorderItem)
      stack.push(node.left)
    }
  }
  return root
};
// @lc code=end
// 递归版
// var buildTree = function(inorder, postorder) {
//   if (!inorder.length) return null
//   const node = new TreeNode()
//   findNode(inorder, postorder, node)
//   return node
// };

// var findNode = (inorder, postorder, node) => {
//   if (!inorder.length) return
//   const lastPostorder = postorder[postorder.length - 1]
//   node.val = lastPostorder
//   const inorederIndex = inorder.findIndex(item => item === lastPostorder)
//   const inorderLeft = inorder.slice(0, inorederIndex)
//   const inorderRight = inorder.slice(inorederIndex + 1)
//   const postorderLeft = postorder.filter(item => inorderLeft.includes(item))
//   const postorderRight = postorder.filter(item => inorderRight.includes(item))
  
//   if (inorderLeft.length) {
//     node.left = new TreeNode()
//     findNode(inorderLeft, postorderLeft, node.left)
//   }
//   if (inorderRight.length) {
//     node.right = new TreeNode()
//     findNode(inorderRight, postorderRight, node.right)
//   }
// }
